package com.tjian.fafa.user.base;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Typeface;
import android.os.Bundle;
import android.os.Looper;
import android.text.method.PasswordTransformationMethod;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.Toast;

import com.tjian.fafa.user.R;
import com.tjian.fafa.user.base.bean.UserInfo;
import com.tjian.fafa.user.base.commons.GlobalErrors;
import com.tjian.fafa.user.base.commons.GlobalMsgTypes;
import com.tjian.fafa.user.base.commons.GlobalStrings;
import com.tjian.fafa.user.base.myNetwork.NetworkService;

import java.util.Timer;

public class RegisterActivity extends Activity
{

    private static RegisterActivity mInstance;

    private EditText mEtNickname;
    private EditText mEtPassword;
    private EditText mEtConfirmPassword;
    private Spinner mSpBirthYear;
    private Spinner mSpBirthMonth;
    private Spinner mSpBirthDay;
    private RadioGroup mRgpSex;
    private UserInfo mUserInfo;

    private Button mBtnRegister;
    private Button recarindex;//注册成功页面返回按钮

    public UserInfo mUserAfterRegister;
    public boolean mReceivedRegister;
    Timer timer = new Timer();//timer中有一个线程,这个线程不断执行task


    public static RegisterActivity getInstance()
    {
        return mInstance;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {

        super.onCreate(savedInstanceState);
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.main_register);

        mInstance = this;

        mEtNickname = (EditText) findViewById(R.id.main_register_edittext_nickname);
        mEtPassword = (EditText) findViewById(R.id.main_register_edittext_password);
        mEtConfirmPassword = (EditText) findViewById(R.id.main_register_edittext_confirm_password);
        mSpBirthYear = (Spinner) findViewById(R.id.main_register_spinner_year);
        mSpBirthMonth = (Spinner) findViewById(R.id.main_register_spinner_month);
        mSpBirthDay = (Spinner) findViewById(R.id.main_register_spinner_day);
        mRgpSex = (RadioGroup) findViewById(R.id.mainRegisterRgpChooseSex);

        /* this is to render the password edittext font to be default */
        mEtPassword.setTypeface(Typeface.DEFAULT);
        mEtPassword.setTransformationMethod(new PasswordTransformationMethod());
        mEtConfirmPassword.setTypeface(Typeface.DEFAULT);
        mEtConfirmPassword.setTransformationMethod(new PasswordTransformationMethod());

        mBtnRegister = (Button) findViewById(R.id.main_register_btn_register);

        mBtnRegister.setOnClickListener(new OnClickListener()
        {
            @Override
            public void onClick(View v)
            {

                String name = mEtNickname.getText().toString().trim();
                String password = mEtPassword.getText().toString().trim();
                String confirmPassword = mEtConfirmPassword.getText().toString().trim();

                int birthYear = mSpBirthYear.getSelectedItemPosition() + 1941;
                int birthMonth = mSpBirthMonth.getSelectedItemPosition() + 1;
                int birthDay = mSpBirthDay.getSelectedItemPosition() + 1;

                int sex = 0;
                int sexChoseId = mRgpSex.getCheckedRadioButtonId();
                switch (sexChoseId)
                {
                    case R.id.mainRegisterRdBtnFemale:
                        sex = 0;
                        break;
                    case R.id.mainRegisterRdBtnMale:
                        sex = 1;
                        break;
                    default:
                        sex = -1;
                        break;
                }

                if (name.equals(""))
                {
                    Toast.makeText(RegisterActivity.this, "请填写正确的用户名", Toast.LENGTH_SHORT).show();
                    return;
                }
                else if (password.length() < 5)
                {
                    Toast.makeText(RegisterActivity.this, "密码不能小于5位", Toast.LENGTH_SHORT).show();
                    return;
                }
                else if (!password.equals(confirmPassword))
                {
                    Toast.makeText(RegisterActivity.this, "两次输入密码不相同", Toast.LENGTH_SHORT).show();
                    return;
                }
                else if (sex < 0)
                {
                    Toast.makeText(RegisterActivity.this, "请选择性别", Toast.LENGTH_SHORT).show();
                    return;
                }


                tryRegister(name, password, birthYear, birthMonth, birthDay, sex);
            }

        });
    }

    @Override
    public void onDestroy()
    {
        super.onDestroy();
        mInstance = null;
    }

    @Override
    public void onBackPressed()
    {
        super.onBackPressed();
        finish();   // destroy RegisterActivity when leave
    }

    public void tryRegister(String name, String password, int birthYear, int birthMonth, int birthDay, int sex)
    {
        UserInfo uu0 = new UserInfo(name, 0, sex, birthYear, birthMonth, birthDay, 0);

        //uponRegister(name, birthYear,birthMonth, birthDay,sex);

        String toRegister = uu0.toString() + GlobalStrings.signupDivider +
                password + GlobalStrings.signupDivider;
        Log.i("aa", toRegister);
        NetworkService.getInstance().closeConnection();
        NetworkService.getInstance().onInit(this);
        NetworkService.getInstance().setupConnection();
        if (NetworkService.getInstance().getIsConnected())
        {
            Log.i("bb", "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa");
            NetworkService.getInstance().sendUpload(GlobalMsgTypes.msgSignUp, toRegister);

        }
        else
        {
            NetworkService.getInstance().closeConnection();
            Toast.makeText(this, "failed to connect to Server", Toast.LENGTH_LONG).show();
            return;
        }


        //		con.closeNetConnect();
    }

    public void regturnindex()
    {

        Intent intent = new Intent(RegisterActivity.this, regReturnPage.class);
        startActivity(intent);
        finish();

    }

    public void uponRegister(String msg0)
    {
        Log.i("ddd", "接受成功=" + msg0);
        String msg1 = "";
        final String strSplitter = GlobalStrings.entityDivider;
        String[] sbArr0 = msg0.split(strSplitter);
        for (int i = 0; i <= 10; i++)
        {
            msg1 += sbArr0[i];
            msg1 += strSplitter;
        }
        msg1 += "imgs/avatar/2014/12/27/haoren.jpg" + strSplitter;

        mUserAfterRegister = new UserInfo(msg1);
        mReceivedRegister = true;//注册成功
        Log.i("mReceivedRegister", "mReceivedRegister=" + mReceivedRegister);

        while (!mReceivedRegister)
        {
            Looper.prepare();
            Toast.makeText(RegisterActivity.this, "注册失败", Toast.LENGTH_SHORT).show();
            Looper.loop();

            return;//
        }
        if (mUserAfterRegister.getId() == GlobalErrors.nameAlreadyExists)
        {
            Looper.prepare();
            Toast.makeText(RegisterActivity.this, "用户名已经存在", Toast.LENGTH_SHORT).show();
            Looper.loop();
            setContentView(R.layout.main_register);

        }
        else if (mUserAfterRegister.getId() >= 0)
        {
            Looper.prepare();
            Toast.makeText(RegisterActivity.this, "注册成功", Toast.LENGTH_SHORT).show();
            mUserInfo = new UserInfo(mUserAfterRegister.getName(), 0, 0, 0, 0, 0, 0);

            ConnectedApp connected_app0 = ConnectedApp.getInstance();
            connected_app0.setUserInfo(mUserInfo);
            connected_app0.clearListActivity();
            connected_app0.instantiateListActivity();
            //Looper.loop();
            regturnindex();


        }
        else
        {
            Looper.prepare();
            Toast.makeText(RegisterActivity.this, "未注册成功", Toast.LENGTH_SHORT).show();
            Looper.loop();
            setContentView(R.layout.main_register);

        }
        regturnindex();
    }
    /*public void uponRegister(String name,  int birthYear, int birthMonth, int birthDay, int sex) {
        mUserAfterRegister = new UserInfo(name, birthYear,birthMonth, birthDay,sex);
    	mReceivedRegister = true;
    }*/

}